<template>
  <div class="container">
    <router-link to="/knowledge_bases" class="nav-link"
      >返回知识库管理</router-link
    >
    <h1>知识库创建</h1>

    <div class="main-content">
      <div class="sidebar">
        <div
          class="tab"
          :class="{ active: activeTab === 'general' }"
          @click="switchTab('general')"
        >
          常规设置
        </div>
        <div
          class="tab"
          :class="{ active: activeTab === 'advanced' }"
          @click="switchTab('advanced')"
        >
          高级设置
        </div>
      </div>

      <div id="general" class="tab-content" v-show="activeTab === 'general'">
        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label for="name">知识库名称</label>
            <input type="text" id="name" v-model="formData.name" required />
          </div>

          <div class="form-group">
            <label for="embedding-model">嵌入模型</label>
            <select id="embedding-model" v-model="formData.embedding_model">
              <option value="nomic-embed-text:latest">
                nomic-embed-text:latest
              </option>
              <option value="bge-large-zh-v1.5">bge-large-zh-v1.5</option>
              <option value="text-embedding-ada-002">
                text-embedding-ada-002
              </option>
            </select>
          </div>

          <div class="form-group">
            <label for="embedding-dim">嵌入维度</label>
            <input
              type="text"
              id="embedding-dim"
              v-model="formData.embedding_dimension"
              placeholder="留空表示不设置"
            />
          </div>

          <div class="form-group">
            <label for="rerank-model">重排模型</label>
            <select id="rerank-model" v-model="formData.rerank_model">
              <option value="">没有模型</option>
              <option value="bge-reranker-base">bge-reranker-base</option>
              <option value="bge-reranker-large">bge-reranker-large</option>
            </select>
          </div>

          <div class="form-group">
            <label for="doc-processor">文档处理工具</label>
            <select id="doc-processor" v-model="formData.doc_processor">
              <option value="MinerU">MinerU</option>
              <option value="simple">简单处理</option>
            </select>
          </div>

          <div class="form-group">
            <label for="doc-segments">请求文档片段数量</label>
            <div class="slider-container">
              <input
                type="range"
                min="1"
                max="50"
                v-model="formData.chunk_count"
                class="slider"
                id="doc-segments"
              />
              <div class="slider-value" id="doc-segments-value">
                {{ formData.chunk_count }}
              </div>
            </div>
          </div>
        </form>
      </div>

      <div id="advanced" class="tab-content" v-show="activeTab === 'advanced'">
        <div class="form-group">
          <label for="chunk-size">分段大小</label>
          <input
            type="text"
            id="chunk-size"
            v-model="formData.chunk_size"
            placeholder="默认值（不建议修改）"
          />
        </div>

        <div class="form-group">
          <label for="overlap-size">重叠大小</label>
          <input
            type="text"
            id="overlap-size"
            v-model="formData.overlap_size"
            placeholder="默认值（不建议修改）"
          />
        </div>

        <div class="form-group">
          <label for="matching-threshold">匹配度阈值</label>
          <input
            type="text"
            id="matching-threshold"
            v-model="formData.matching_threshold"
            placeholder="未设置"
          />
        </div>

        <div class="alert alert-warning">
          <strong>注意：</strong>分段大小和重叠大小修改只针对新添加的内容有效
        </div>
      </div>
    </div>

    <div class="button-group">
      <button id="cancel-btn" type="button" @click="handleCancel">取消</button>
      <button id="save-btn" @click="handleSubmit">确定</button>
    </div>

    <div id="result" v-if="resultMessage" :class="['alert', resultType]">
      <strong>{{ resultType === 'alert-success' ? '成功：' : '失败：' }}</strong
      >{{ resultMessage }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'KnowledgeBaseCreate',
  data() {
    return {
      activeTab: 'general',
      resultMessage: '',
      resultType: '',
      formData: {
        name: '',
        embedding_model: 'nomic-embed-text:latest',
        embedding_dimension: '1024',
        rerank_model: '',
        chunk_count: 10,
        chunk_size: '',
        overlap_size: '',
        matching_threshold: '',
        doc_processor: 'MinerU',
      },
    }
  },
  methods: {
    // 切换选项卡
    switchTab(tabId) {
      this.activeTab = tabId
    },

    // 处理表单提交
    handleSubmit() {
      // 验证表单
      if (!this.formData.name) {
        this.$message.warning('请输入知识库名称')
        return
      }

      // 准备提交数据
      const submitData = {
        ...this.formData,
        embedding_dimension: this.formData.embedding_dimension
          ? parseInt(this.formData.embedding_dimension)
          : 1024,
        chunk_count: parseInt(this.formData.chunk_count),
        chunk_size: this.formData.chunk_size
          ? parseInt(this.formData.chunk_size)
          : undefined,
        overlap_size: this.formData.overlap_size
          ? parseInt(this.formData.overlap_size)
          : undefined,
        matching_threshold: this.formData.matching_threshold
          ? parseFloat(this.formData.matching_threshold)
          : undefined,
      }

      // 移除未定义或空值的字段
      Object.keys(submitData).forEach((key) => {
        if (submitData[key] === undefined || submitData[key] === '') {
          delete submitData[key]
        }
      })

      // 发送请求到服务器
      this.$http
        .post('/create-knowledge-base', submitData)
        .then((response) => {
          const data = response
          if (data) {
            this.resultType = 'alert-success'
            this.resultMessage = data.message
            this.$message.success('创建成功')
            // 2秒后跳转到知识库管理页面
            setTimeout(() => {
              this.$router.push('/knowledge_bases')
            }, 2000)
          } else {
            this.resultType = 'alert-error'
            this.resultMessage = data.error
          }
        })
        .catch((error) => {
          this.resultType = 'alert-error'
          this.resultMessage = error.message || '创建知识库失败'
          console.error('创建知识库失败:', error)
        })
    },

    // 处理取消按钮点击
    handleCancel() {
      this.$router.push('/knowledge_bases')
    },
  },
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  /* max-width: 900px;
  margin: 20px auto; */
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
}

.main-content {
  display: flex;
  flex-direction: row;
  flex: 1;
}

.sidebar {
  width: 200px;
  margin-right: 20px;
  background-color: #f8f9fa;
  border-radius: 5px;
  padding: 10px 0;
}

.tab {
  padding: 15px 20px;
  cursor: pointer;
  border-left: 3px solid transparent;
  transition: all 0.3s ease;
}

.tab:hover {
  background-color: #e9ecef;
}

.tab.active {
  background-color: #fff;
  border-left: 3px solid #3498db;
  color: #3498db;
  font-weight: bold;
}

.tab-content {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
}

input[type='text'],
select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.slider-container {
  margin: 15px 0;
}

.slider {
  width: 100%;
}

.slider-value {
  text-align: center;
  margin-top: 5px;
  font-weight: bold;
}

button {
  background-color: #3498db;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1em;
  margin-right: 10px;
}

button:hover {
  background-color: #2980b9;
}

.button-group {
  margin-top: 30px;
  text-align: right;
  padding-right: 20px;
}

.alert {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.alert-success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.alert-error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.alert-warning {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeeba;
}

.nav-link {
  display: inline-block;
  margin-bottom: 20px;
  color: #3498db;
  text-decoration: none;
  font-weight: bold;
}

.nav-link:hover {
  text-decoration: underline;
}
</style>
